package com.znxz.hzqiuxm.ziniublog.user.domain.valobj;

import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;
import org.bson.types.ObjectId;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.time.LocalDateTime;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Copyright © 2018年 ziniuxiaozhu. All rights reserved.
 *
 * @Author 临江仙 hzqiuxm@163.com
 * 专门用来进行用户认证的实体类，需要实现SpringSecurity的UserDetails接口
 * @Date 2018/8/31 13:44
 */
@Data
public class JwtUser implements UserDetails{

    /**
     * 用户编号
     */
    private final ObjectId userId;

    /**
     * 用户名称
     */
    private final String username;
    /**
     * 用户花名
     */
    private final String showname;
    /**
     * 密码
     */
    private final String password;
    /**
     * 邮件
     */
    private final String email;

    /**
     * 登录安全鉴权
     */
    @JsonIgnore
    private final LoginSecurity loginSecurity;
    /**
     * 角色
     */
    private final List<String> roles;

    /**
     * 过期时间
     */
    private final Date expiration;

    public JwtUser(ObjectId userId, String username, String showname, String password, String email, LoginSecurity loginSecurity, List<String> roles, Date expiration) {
        this.userId = userId;
        this.username = username;
        this.showname = showname;
        this.password = password;
        this.email = email;
        this.loginSecurity = loginSecurity;
        this.roles = roles;
        this.expiration = expiration;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return  roles.stream()
                .map(SimpleGrantedAuthority::new)
                .collect(Collectors.toList());
    }

    @JsonIgnore
    @Override
    public String getPassword() {
        return password;
    }

    @Override
    public String getUsername() {
        return username;
    }

    /**
     * 账号是否未过期
     * @return
     */
    @JsonIgnore
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }


    /**
     * 账号是否未锁定
     * @return
     */
    @JsonIgnore
    @Override
    public boolean isAccountNonLocked() {
        return true;
    }


    /**
     * 密码是否未过期
     * @return
     */
    @JsonIgnore
    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }


    /**
     * 账号是否激活
     * @return
     */
    @JsonIgnore
    @Override
    public boolean isEnabled() {
        return true;
    }
}
